﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace GameDriver
{
    /// <summary>
    /// A completely static class used to track errors in an easily accessible log.
    /// </summary>
    public static class ErrorLog
    {
        private static TextWriter errorFile;

        /// <summary>
        /// Initializes the error log file with the proper header - should be called once at initialization.
        /// </summary>
        /// <param name="title">The game title to use in the error file's header.</param>
        public static void Initialize(string title = "")
        {
            errorFile = new StreamWriter("error_log.txt", false);

            if (title != "") title += " "; //Maintain appropriate spacing.
            string header = "+ " + title.ToUpper() + "ERROR LOG: " + DateTime.Now.ToShortDateString() + 
                                ", " + DateTime.Now.ToShortTimeString() + " +";

            errorFile.WriteLine(new String('+', header.Length));
            errorFile.WriteLine(header);
            errorFile.WriteLine(new String('+', header.Length));

            errorFile.Close();
        }

        /// <summary>
        /// Add an error log to the error file with file, line, column and method information.
        /// </summary>
        /// <param name="msg">The error message to log.</param>
        public static void Log(string msg)
        {
            StackFrame stackFrame = new StackFrame(1, true);
            string method = stackFrame.GetMethod().ToString();
            int line = stackFrame.GetFileLineNumber();
            int col = stackFrame.GetFileColumnNumber();
            string file = stackFrame.GetFileName();

            #if (DEBUG) //This checks  to see if the build is the DEBUG build, and if it's not, doesn't keep the error log.
                        errorFile = new StreamWriter("error_log.txt", true);
                        errorFile.WriteLine();
                        errorFile.WriteLine(file);
                        errorFile.WriteLine("  (" + line + "," + col + "): " + method);
                        errorFile.WriteLine("  Error: " + msg);
                        errorFile.Close();
            #endif
        }
    }
}
